package com.xqyq.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xqyq.model.Match;
import com.xqyq.model.Sign;
import com.xqyq.model.User;
import com.xqyq.service.MatchService;
import com.xqyq.service.ReportService;
import com.xqyq.service.SignService;
import com.xqyq.service.UserService;
import com.xqyq.util.JavaMail;

@Controller
public class UserController {
	@Autowired
	public ReportService reportService;
	@Autowired
	public MatchService matchService;
	@Autowired
	public SignService signService;
	@Autowired
	public UserService userService;

	@RequestMapping(value = "/toHome")
	public String home(HttpServletRequest request) {
		List<Match> matchList = matchService.getPublishMatch(6);
		List<Match> matchPhotoList = new ArrayList<Match>();

		System.out.println(matchList.size());

		for (int i = 0; i < 6 && i < matchList.size(); i++) {
			matchPhotoList.add(matchList.get(i));

		}
		request.setAttribute("matchPhotoList", matchPhotoList);
		request.setAttribute("matchList", matchList);

//		List<Report> reportList = reportService.getReports(6);
//		List<Report> reportPhotoList = new ArrayList<Report>();
//		for (int i = 0; i < 2 && i < reportList.size(); i++) {
//			reportPhotoList.add(reportList.get(i));
//		}
//		request.setAttribute("reportPhotoList", reportPhotoList);
//		request.setAttribute("reportList", reportList);

		return "front/index";
	}

	@RequestMapping(value = "/user/myhome.html")
	public String toMyHome(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		List<Sign> signList = signService.getUserSignList(user.getUse_id());
		request.setAttribute("signList", signList);
		return "front/myhome";
	}

	@RequestMapping("/user/myzoom.html")
	public String info() {
		return "front/myzoom";
	}

	@RequestMapping("/user/api_changeInfo")
	@ResponseBody
	public String changeInfo(User user, HttpServletRequest request) {
		User userOld = (User) request.getSession().getAttribute("user");
	
		userOld.setHead_photo(user.getHead_photo());
		userOld.setUser_name(user.getUser_name());
		userOld.setPhone(user.getPhone());
		userOld.setDetailaddress(user.getDetailaddress());
		userOld.setGraduate_year(user.getGraduate_year());
		userOld.setProfile(user.getProfile());
		userOld.setStudentId(user.getStudentId());
		
		userService.update(userOld);
		return "{\"state\":200,\"comment\":\"修改成功。\"}";
	}

	@RequestMapping("/user_info.html")
	public String user_info(@RequestParam("user_id") int user_id,
			HttpServletRequest request) {
		User userInfo = userService.get(user_id);
		request.setAttribute("userInfo", userInfo);
		return "front/other_user_info";
	}

	@RequestMapping(value = "/forgetpwd.html")
	public String forgetPass(HttpServletRequest req, HttpServletResponse res) {
		return "front/forgetpwd";
	}

	@RequestMapping(value = "/sendFindMail")
	public String sendFindMail(HttpServletRequest req, String email,
			ModelAndView model) {
		System.out.println("邮箱不存在,你不会忘记了吧?");
		User user = userService.findUserByEmail(email);

		System.out.println(user);

		HashMap<String, String> map = new HashMap<String, String>();
		String tip = "";
		if (user == null) { // 用户名不存在
			tip = "邮箱不存在,你不会忘记了吧?";
			map.put("tip", tip);

			System.out.println("邮箱不存在,你不会忘记了吧?");
			model.addObject(map);
			return "front/forgetpwd";
		}

		try {

			String secretKey = DigestUtils.md5DigestAsHex(req.getSession()
					.getId().getBytes()); // 密钥 Timestamp

			System.out.println("secretKey:" + secretKey);
			Date outDate = new Timestamp(
					System.currentTimeMillis() + 5 * 60 * 1000);// 30分钟后过期
			/*
			 * long date = outDate.getTime() / 1000 * 1000;// 忽略毫秒数
			 */
			// user.setCode(secretKey);
			// user.setRegisterDate(outDate);
			// System.out.println(outDate);
			// userService.update(user, req);// 保存到数据库
			/* String key = user.getEmail() + "$" + date + "$" + secretKey; */

			String emailTitle = "密码找回";
			String path = req.getContextPath();
			String basePath = req.getScheme() + "://" + req.getServerName()
					+ ":" + req.getServerPort() + path + "/";
			String resetPassHref = basePath + "reset_password?key=" + secretKey
					+ "&email=" + user.getMail();
			String emailContent = "您的登陆信息： Email：" + user.getMail()
					+ "<br/><a href=" + resetPassHref
					+ " target='_BLANK'>点击我重新设置密码</a>"
					+ "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'";
			System.out.print(resetPassHref);

			JavaMail.sendMail(emailTitle, emailContent, user.getMail());
			tip = "操作成功,已经发送找回密码链接到您邮箱。请在30分钟内重置密码";
			/* logInfo(req, email, "申请找回密码"); */
		} catch (Exception e) {
			e.printStackTrace();
			tip = "邮箱不存在？未知错误,联系管理员吧。";
		}
		map.put("tip", tip);
		model.addObject(map);
		return "front/login";
	}

	@RequestMapping(value = "/reset_password", method = RequestMethod.GET)
	public ModelAndView checkResetLink(String key, String email,
			HttpServletRequest req) {
		ModelAndView model = new ModelAndView("tip");
		String tip = "";
		if (key.equals("") || email.equals("")) {
			tip = "链接不完整,请重新生成";
			model.addObject("tip", tip);
			System.out.println(tip);
			return model;
		}
		User user = userService.findUserByEmail(email);
		if (user == null) {
			tip = "链接错误,无法找到匹配用户,请重新申请找回密码.";
			model.addObject("tip", tip);
			System.out.println(tip);
			return model;
		}
		/*
		 * Date outDate = user.getRegisterDate(); if (outDate.getTime() <=
		 * System.currentTimeMillis()) { // 表示已经过期 tip = "链接已经过期,请重新申请找回密码.";
		 * model.addObject("tip", tip); System.out.println(tip); return model; }
		 * if (!user.getCode().equals(key)) { tip = "链接不正确,Code不正确了?重新申请吧";
		 * model.addObject("tip", tip); System.out.println(tip); return model; }
		 */

		model.setViewName("front/resetpwd"); // 返回到修改密码的界面
		model.addObject("email", email);
		model.addObject("code", key);
		return model;
	}

	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
	public String updateUser(HttpServletRequest req) {
		User user = userService.findUserByEmail(req.getParameter("mail"));
		if (user == null) {
			req.setAttribute("tip", "修改失败");
			return "front/login";

		}
		user.setPassword(req.getParameter("password"));
		userService.update(user);

		return "front/login";
	}

	@RequestMapping(value = "/checkMail", method = RequestMethod.POST)
	@ResponseBody
	public String checkMail(String mail) {
		
		if(mail == null){
			return "{\"state\":104,\"comment\":\"邮箱错误。\"}";
		}
		
		User user = userService.findUserByEmail(mail);
		if (user == null) {
			return "{\"state\":200,\"comment\":\"邮箱可以使用。\"}";
		} else {
			return "{\"state\":104,\"comment\":\"邮箱已被注册。\"}";
		}
	}

	
	@RequestMapping(value = "/toCkeditor")
	private String toCkeditor(){
		System.out.println("ss");
		return "front/ckeditor";
	}
}
